#include <Arduino.h>
#include "hub75e.h"
#include "analog_clock.h"
#include "clock_manager.h"
#include "espWifiCfg.h"
#include "ntpTime.h"
#include "display_config.h"

// 引脚定义 (保持原始顺序)
const uint8_t pins[14] = {13, 27, 5, 21, 22, 23, 25, 26, 14, 15, 16, 17, 18, 19};

Panel panel(DISPLAY_WIDTH, DISPLAY_HEIGHT, NUM_SCAN, pins);
EspWifiCfg wifiCfg;
NTPTime ntpTime;

// 状态变量
bool wifiConnected = false;
unsigned long lastTimeUpdate = 0;
unsigned long lastClockUpdate = 0;
unsigned long lastNTPAttempt = 0;
const unsigned long NTP_UPDATE_INTERVAL = 3600000;
const unsigned long CLOCK_UPDATE_INTERVAL = 1000;

// 绘制状态信息（使用 panel.width / panel.height，避免 relying on macros at runtime）
void drawStatusInfo() {
    uint16_t w = panel.width;
    uint16_t h = panel.height;
    // 使用 panel.height 作为纵向分割线以保留以前行为（右侧用于状态显示）
    uint16_t splitX = (h < w) ? h : (w - 1);
    panel.fillRect(splitX, 0, w - 1, h - 1, 0, 0, 0);

    // WiFi状态指示
    const uint16_t indicatorSize = 5; // size of the small status squares

    // Move green/red indicator to the top-left corner (0,0)
    if (wifiConnected) {
        panel.fillRect(0, 0, indicatorSize, indicatorSize, 0, 255, 0);  // green at (0,0)
    } else {
        panel.fillRect(0, 0, indicatorSize, indicatorSize, 255, 0, 0);  // red at (0,0)
    }

    // Time sync indicator: place at the upper-right corner of the left panel (just left of splitX)
    // clamp coordinates to avoid underflow for very small panels
    uint16_t rightMostLeftX = (splitX > 0) ? (splitX - 1) : 0;
    uint16_t blueX1 = rightMostLeftX;
    uint16_t blueX0 = (blueX1 > indicatorSize) ? (blueX1 - indicatorSize) : 0;
    uint16_t blueY0 = 0;
    uint16_t blueY1 = indicatorSize;

    if (ntpTime.isTimeValid()) {
        // draw blue block at upper-right of left panel
        panel.fillRect(blueX0, blueY0, blueX1, blueY1, 0, 0, 255);
    } else {
        // draw yellow block at the same upper-right position to indicate time not synced
        panel.fillRect(blueX0, blueY0, blueX1, blueY1, 255, 255, 0);
    }
}

void setup() {
    Serial.begin(115200);
    panel.begin();
    wifiCfg.begin();
    ntpTime.begin();
    ntpTime.setTimezone(8);

    panel.clearScreen();
    Serial.println("ESP32 LED clock started");
}

void loop() {
    wifiCfg.loop();

    // 检查WiFi状态（封装到 EspWifiCfg）
    wifiCfg.updateWifiStatus(wifiConnected, lastNTPAttempt);

    // NTP时间同步（封装到 NTPTime）
    if (wifiConnected) {
        ntpTime.attemptSyncIfNeeded(lastNTPAttempt, 30000);
    }

    // 更新时钟显示（封装到 clock_manager）
    if (maybeUpdateClock(panel, ntpTime, lastClockUpdate, CLOCK_UPDATE_INTERVAL)) {
        drawStatusInfo();
    }

    // 调试信息（每5秒打印一次）
    static unsigned long lastDebug = 0;
    if (millis() - lastDebug > 5000) {
        lastDebug = millis();
        if (ntpTime.isTimeValid()) {
            Serial.printf("Network time: %s\n", ntpTime.getFormattedTime().c_str());
        } else {
            unsigned long totalSeconds = millis() / 1000;
            uint8_t dbgSecond = totalSeconds % 60;
            uint8_t dbgMinute = (totalSeconds / 60) % 60;
            uint8_t dbgHour = (totalSeconds / 3600) % 24;
            Serial.printf("System time: %02d:%02d:%02d\n", dbgHour, dbgMinute, dbgSecond);
        }
    }

    delay(10);
}